<template>
    <div>
        <div style="display:flex">
            <el-button v-if="isMultiple == true" class="add-obj" style="margin-right:20px" @click="multiDownload"><span style="display:flex">
              <svg-icon icon-class="icon-adding" style="margin-right:1rem;"></svg-icon>
              <h3>批量下载</h3>
              </span></el-button>
              <el-button v-if="isMultiple == true" class="add-obj" style="margin-right:20px" @click="multiDelete"><span style="display:flex">
              <svg-icon icon-class="icon-adding" style="margin-right:1rem;"></svg-icon>
              <h3>批量删除</h3>
              </span></el-button>
        </div>
        
        <el-table 
        :data="tbData" 
        style="width: 100%" 
        :row-class-name="rowClassName"  
        @select="onRowClick"
        @select-all="selectAll"
        @selection-change="handleSelectionChange" >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="name" :show-overflow-tooltip="true" label="名称">
          <template slot-scope="scope">
            <i style="color:#409EFF" class=" el-icon-s-order" />{{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="是否上传成功" width="150">
            <template>上传成功！</template>
        </el-table-column>

        <el-table-column prop="name" label="是否转换成功" width="150">
            <template>转换成功！</template>
        </el-table-column>
        <el-table-column style="text-align:right" width="120" prop="size" label="大小" />
        <el-table-column prop="name" width="250" :show-overflow-tooltip="true" label="功能">
          <template slot-scope="scope">
            <el-button @click="deleteFileByIndexAndFid(scope.$index,scope.row.id)" type="primary" size="mini">删除</el-button>
            <el-button @click="download(scope.row.id)" type="primary" size="mini">下载</el-button>
            <el-button @click="fileRename(scope.$index,scope.row.id,scope.row.name)" type="primary" size="mini">重命名</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
</template>

<script>
let config = {
               headers:{"Authorization": localStorage.getItem("token")}
               };
export default {
    name:'HistoryFileList',
    data(){
        return{
            tbData: [],
            selectFileList:[],
            indexList:[],
            isMultiple:false,
        }
    },
    created:function(){
        // console.log("进入created")
        this.getFileList()
    },
    methods:{
        selectAll(row){
            this.indexList = []
            for (var i = 0; i < row.length; i++) {
            this.indexList.push(row[i].row_index)
            }
            console.log(this.indexList)
        },
        //添加选中索引值
        onRowClick(row) {
            // console.log(row)
            this.indexList = []
            for (var i = 0; i < row.length; i++) {
            this.indexList.push(row[i].row_index)
            }
            console.log(this.indexList)
        },
        //自定义索引值字段
        rowClassName({row, rowIndex}) {
                //把每一行的索引放进row
            row.row_index = rowIndex;
                // console.log(row)
        },
        //批量删除文件
        multiDelete(){
            if(this.selectFileList.length != 0){
                this.selectFileList.forEach(element=>{
                    this.deleteFileByFid(element['id'])
                })
            }else{
                this.$message.error("未选中任何文件!")
            }
            this.indexList.forEach(item=>{
                    console.log(item)
                    this.tbData.splice(item,1)
                })
                setTimeout(() => {
                    this.$router.go(0)
                }, 500);
        },
        //删除文件BY ID
        async deleteFileByFid(fid){
            // console.log(index)
            this.$axios
            .get('/file/deleteFile?fileId='+fid,config)
            .then(res=>{
                console.log(res)
                this.$message.success(res.data.msg)
            }).catch(fault=>{
                this.$message.error(fault)
            })

        },
        //删除文件BY Index And FID
        async deleteFileByIndexAndFid(index,fid){
            // console.log(index)
            this.$axios
            .get('/file/deleteFile?fileId='+fid,config)
            .then(res=>{
                console.log(res)
                this.$message.success(res.data.msg)
                this.tbData.splice(index,1)
            }).catch(fault=>{
                this.$message.error(fault)
            })

        },
    //文件重命名
    fileRename(row,fid,fname){
    // console.log(this.tbData[1])
    // console.log(row)
    this.$prompt('请输入新的文件名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern:/^.{0,15}$/,
          inputErrorMessage:'请输入长度在0-15的字符!',
          inputValue:fname
        }).then(({ value })=>{
          this.$axios
          .get('/file/renameHistoryFile?fid='+fid+'&fname='+value,config)
          .then(res=>{
            this.$message({
              type: 'success',
              message: res.data.msg
          });

          this.tbData[row].name = value
          
          }).catch(()=>{
              this.$message.error('文件重命名失败!')
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: fname + '取消重命名'
          });       
        });
  },
        //批量下载
        multiDownload(){    
            if(this.selectFileList.length != 0){
                this.selectFileList.forEach(element=>{
                    this.download(element['id'])
                })
            }else{
                this.$message.error("未选中任何文件!")
            }
        },
        //下载请求
        async download(fid){
            this.$axios.get('/file/downloadHistoryFile?fileId='+fid,{responseType:'arraybuffer'},config)
            .then(res=>{
                // console.log(res)
                // console.log(res.headers["content-type"])
                // console.log(res.headers["content-disposition"].split(";")[1].split("=")[1])
                const fileName = res.headers["content-disposition"].split(";")[1].split("=")[1]
                let blob = new Blob([res.data]);
                // console.log(blob)
                let link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = fileName;
                link.click();
            })
        },
        //获取文件列表
        getFileList(){
            this.$axios
            .get('/file/getOutputFileList',config)
            .then(res=>{
                let data = res.data.data;
                var dataList = []
                data.forEach(element => {
                // console.log(element['fileName'])
                let jsonData = {}
                jsonData['id'] = element['id']
                jsonData['name'] = element['fileName']
                let size =parseInt(element['fileSize'] / 1024)
                // console.log(size)
                if(size >= 1024){
                    jsonData['size'] = parseInt(size / 1024) + ' MB'
                }else{
                    jsonData['size'] = size + ' KB'
                }
                dataList.push(jsonData)
                });
                this.tbData = dataList
            })
        },
        handleSelectionChange(arr){
            // console.log(arr)
            if(arr.length == 0){
            this.selectFileList = []
            this.isMultiple = false
            }else{
            this.selectFileList = arr
            this.isMultiple = true
            }
        },

    }
}
</script>

<style>
.add-obj {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 9rem;
  height: 2.5rem;
  border: none;

  color: var(--BG);
  font-size: 0.75rem;
  line-height: 1rem;
  border-radius: 0.7rem;
  background-color: var(--Theme-6);
  cursor: pointer;
}
.add-obj:hover {
  background-color: var(--Theme-7);
}
.add-obj:active {
  background-color: var(--Theme-8);
}
</style>